from datetime import datetime
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Float, Text, Enum, Table, Boolean
from sqlalchemy.orm import relationship

from app.models.base import Base

# 用户-知识点关联表（选课/学习关系）
user_knowledge_enrollments = Table(
    'user_knowledge_enrollments',
    Base.metadata,
    Column('user_id', Integer, ForeignKey('users.id'), primary_key=True),
    Column('knowledge_id', Integer, ForeignKey('knowledge_base.id'), primary_key=True),
    Column('enrolled_at', DateTime, default=datetime.utcnow),
    Column('status', String(20), default='active'),  # active, completed, dropped
    Column('progress', Float, default=0.0)  # 学习进度
)

class KnowledgeBase(Base):
    """知识库模型（整合课程功能）"""
    __tablename__ = "knowledge_base"

    id = Column(Integer, primary_key=True, index=True)
    subject = Column(String(50), nullable=False, comment="科目")
    level = Column(String(10), comment="级别")
    chapter = Column(String(100), default="第一章", comment="章节")
    knowledge_point = Column(Text, comment="知识点")
    content = Column(Text, nullable=False, comment="学习内容")
    extended_content = Column(Text, comment="扩展内容")

    # 课程相关字段
    is_course = Column(Boolean, default=False, comment="是否作为课程")
    title = Column(String(100), comment="课程名称（当作为课程时使用）")
    description = Column(Text, comment="课程描述")
    credits = Column(Integer, default=0, comment="学分")
    duration = Column(Integer, comment="课程时长(小时)")
    prerequisites = Column(Text, comment="先修要求")

    study_count = Column(Integer, default=0, comment="学习次数")
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    # 关联关系
    exercises = relationship("Exercise", back_populates="knowledge", cascade="all, delete-orphan")
    enrolled_users = relationship("User", secondary="user_knowledge_enrollments", back_populates="enrolled_knowledge")

class Exercise(Base):
    """习题模型"""
    __tablename__ = "exercises"

    id = Column(Integer, primary_key=True, index=True)
    knowledge_id = Column(Integer, ForeignKey("knowledge_base.id"))
    question = Column(Text, nullable=False, comment="习题内容")
    answer = Column(Text, nullable=False, comment="习题答案")
    attempt_count = Column(Integer, default=0, comment="答题次数")
    correct_count = Column(Integer, default=0, comment="答对次数")
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    # 关联关系
    knowledge = relationship("KnowledgeBase", back_populates="exercises")

class LearningPlan(Base):
    """学习计划模型"""
    __tablename__ = "learning_plans"

    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"))
    knowledge_base_id = Column(Integer, ForeignKey("knowledge_base.id"), nullable=True)
    title = Column(String(100), nullable=False)
    description = Column(Text)
    subject = Column(String(50))
    grade_level = Column(String(20))
    start_date = Column(DateTime)
    end_date = Column(DateTime)
    status = Column(String(20), default="active")  # active, completed, paused
    progress = Column(Integer, default=0)  # 学习计划的整体进度（百分比）
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    # 关联关系
    user = relationship("User", back_populates="learning_plans")
    knowledge_base = relationship("KnowledgeBase")
    tasks = relationship("LearningTask", back_populates="plan", cascade="all, delete-orphan")

class LearningTask(Base):
    """学习任务模型"""
    __tablename__ = "learning_tasks"

    id = Column(Integer, primary_key=True, index=True)
    plan_id = Column(Integer, ForeignKey("learning_plans.id"))
    title = Column(String(100), nullable=False)
    description = Column(Text)
    priority = Column(Integer, default=1)  # 1: 低, 2: 中, 3: 高
    duration = Column(Integer)  # 预计时长（分钟）
    due_date = Column(DateTime)
    status = Column(String(20), default="pending")  # pending, in_progress, completed
    completion_rate = Column(Float, default=0.0)
    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    # 关联关系
    plan = relationship("LearningPlan", back_populates="tasks")
    progress_records = relationship("Progress", back_populates="task", cascade="all, delete-orphan")

class Progress(Base):
    """进度记录模型"""
    __tablename__ = "progress_records"

    id = Column(Integer, primary_key=True, index=True)
    task_id = Column(Integer, ForeignKey("learning_tasks.id"))
    user_id = Column(Integer, ForeignKey("users.id"))
    status = Column(String(20), nullable=False)
    notes = Column(Text)
    time_spent = Column(Integer)  # 花费时间（分钟）
    rating = Column(Integer)  # 难度评分 1-5
    created_at = Column(DateTime, default=datetime.utcnow)

    # 关联关系
    task = relationship("LearningTask", back_populates="progress_records")
    user = relationship("User", back_populates="progress_records")